package com.littlebee.storychild.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.littlebee.storychild.R;
import com.littlebee.storychild.common.utils.BabyStoryPlanEntry;
import com.littlebee.storychild.common.utils.Constant;
import com.littlebee.storychild.common.utils.DateUtils;
import com.littlebee.storychild.common.utils.NetWorkUtils;
import com.littlebee.storychild.common.utils.SoundMeter;
import com.littlebee.storychild.common.utils.ToastUtil;
import com.littlebee.storychild.common.utils.Utils;
import com.littlebee.storychild.ui.entry.Cartoons;
import com.littlebee.storychild.ui.entry.StorysEntry;
import com.littlebee.storychild.ui.entry.User;
import com.zss.library.utils.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 *
 */
public class FirstMotherDialog extends Dialog implements View.OnClickListener {

    private TextView toSend, againRec;
    Activity mContext;
    BabyStoryPlanEntry hid;
    Cartoons hid1;
    StorysEntry hid2;
    private ImageView volume;
    SharedPreferences sp;
    RelativeLayout show_bg;
    LinearLayout show_ly_order;
    Handler myhandler;
    /**
     * 录音提示类型 0 故事选择 1 英语动画片
     */
    private int type;

    public FirstMotherDialog(Activity context, BabyStoryPlanEntry hId, int type) {
        super(context, com.zss.library.R.style.CommonDialog);
        setContentView(R.layout.fragment_first_order);
        this.mContext = context;
        this.type = type;
        sp = mContext.getSharedPreferences(Constant.appName, Context.MODE_PRIVATE); //私有数据

        this.hid = hId;
        int width = android.view.WindowManager.LayoutParams.MATCH_PARENT;
        getWindow().setLayout(width, width);
        initView();
        initData();
    }

    public FirstMotherDialog(Activity context, Cartoons hId, int type) {
        super(context, com.zss.library.R.style.CommonDialog);
        setContentView(R.layout.fragment_first_order);
        this.mContext = context;
        this.type = type;
        sp = mContext.getSharedPreferences(Constant.appName, Context.MODE_PRIVATE); //私有数据
        this.hid1 = hId;
        int width = android.view.WindowManager.LayoutParams.MATCH_PARENT;
        getWindow().setLayout(width, width);
        initView();
        initData();
    }

    public FirstMotherDialog(Activity context, StorysEntry hId, int type) {
        super(context, com.zss.library.R.style.CommonDialog);
        setContentView(R.layout.fragment_first_order);
        this.mContext = context;
        this.type = type;
        sp = mContext.getSharedPreferences(Constant.appName, Context.MODE_PRIVATE); //私有数据
        this.hid2 = hId;
        int width = android.view.WindowManager.LayoutParams.MATCH_PARENT;
        getWindow().setLayout(width, width);
        initView();
        initData();
    }

    public void initView() {
        volume = (ImageView) findViewById(R.id.show_img);
        volume.setOnClickListener(this);
        toSend = (TextView) findViewById(R.id.order_reward);
        toSend.setOnClickListener(this);
        againRec = (TextView) findViewById(R.id.order_res);
        againRec.setOnClickListener(this);
        show_bg = (RelativeLayout) findViewById(R.id.show_bg);
        show_bg.setOnClickListener(this);
        show_ly_order = (LinearLayout) findViewById(R.id.show_ly_order);
        show_ly_order.setOnClickListener(this);
    }

    private void updateDisplay(int signalEMA) {

        switch ((int) signalEMA) {
            case 0:
            case 1:
                volume.setImageResource(R.drawable.ease_record_animate_02);
                break;
            case 2:
            case 3:
                volume.setImageResource(R.drawable.ease_record_animate_04);

                break;
            case 4:
            case 5:
                volume.setImageResource(R.drawable.ease_record_animate_07);
                break;
            case 6:
            case 7:
                volume.setImageResource(R.drawable.ease_record_animate_09);
                break;
            case 8:
            case 9:
                volume.setImageResource(R.drawable.ease_record_animate_11);
                break;
            case 10:
            case 11:
                volume.setImageResource(R.drawable.ease_record_animate_13);
                break;
            default:
                volume.setImageResource(R.drawable.ease_record_animate_14);
                break;
        }
    }

    public void initData() {
        myhandler = new Handler() {
            public void handleMessage(android.os.Message msg) {
                updateDisplay(new Random().nextInt(14));
                sendMessageDelayed(Message.obtain(this, 0x0), 300);
            }
        };
        myhandler.sendMessageDelayed(Message.obtain(myhandler, 0x0), 300);
        if (type == 0) {
            String name = sp.getString("guideselectstory", "");
            if (TextUtils.isEmpty(name)) {
                startPlayer(Constant.FIRST_REC_PATH);
            } else {
                startPlayer(name);

            }
        } else if (type == 1) {
            String name = sp.getString("guidetakephotoaudio", "");
            if (TextUtils.isEmpty(name)) {
                startPlayer(Constant.FIRST_ENG_PATH);
            } else {
                startPlayer(name);

            }
        } else {
            String name = sp.getString("guidethanksaudio", "");
            if (TextUtils.isEmpty(name)) {
                startPlayer(Constant.FIRST_STORY_PATH);
            } else {
                startPlayer(name);

            }

        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.order_reward:
                if (type == 0) {
                    sp.edit().putBoolean("isFirst_Rec", true).commit();
                } else if (type == 1) {
                    sp.edit().putBoolean("isFirst_Eng", true).commit();
                } else {
                    sp.edit().putBoolean("isFirst_Story", true).commit();
                }
                if (type == 1) {
                    MainActivity activity = (MainActivity) mContext;
                    activity.openPhotoPicker(hid1);
                } else {
                    if (type == 0) {
                        RecStoryToMotherDialog dialog = new RecStoryToMotherDialog(mContext, hid, type);
                        dialog.show();
                    } else {
                        RecStoryToMotherDialog dialog1 = new RecStoryToMotherDialog(mContext, hid2, type);
                        dialog1.show();
                    }
                }
                dismiss();
                break;
            case R.id.order_res:
                if (type == 1) {
                    sp.edit().putString("isFirst_Eng_Time","").commit();
                    // TODO: 2017/9/18 去拍照
                    MainActivity activity = (MainActivity) mContext;
                    activity.openPhotoPicker(hid1);
                } else {
                    if (type == 2) {
                        sp.edit().putString("isFirst_Story_Time", "").commit();
                        RecStoryToMotherDialog dialog1 = new RecStoryToMotherDialog(mContext, hid2, type);
                        dialog1.show();
                    } else {
                        RecStoryToMotherDialog dialog1 = new RecStoryToMotherDialog(mContext, hid, type);
                        dialog1.show();
                    }

                }
                dismiss();

                break;
            case R.id.volume:
                if (mPlayer == null) {
                    startPlayer(Constant.FIRST_REC_PATH);
                } else {
                    if (mPlayer.isPlaying()) {
                        mPlayer.pause();
                    } else {
                        mPlayer.start();
                    }
                }
                break;
            case R.id.show_bg:
                dismiss();
                break;
            case R.id.show_ly_order:
                break;


        }
    }

    private MediaPlayer mPlayer = null;

    private void startPlayer(String item) {
        mPlayer = new MediaPlayer();
        mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            public boolean onError(MediaPlayer mp, int what, int extra) {
                mediaRelease();
                myhandler.removeCallbacksAndMessages(null);
                return true;
            }
        });
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mediaRelease();
                againRec.performClick();

            }
        });
        try {
            mPlayer.setDataSource(item);
            final AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
            if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
                mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mPlayer.setLooping(false);
                mPlayer.prepare();
                mPlayer.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void mediaRelease() {
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
        myhandler.removeCallbacksAndMessages(null);
    }


    @Override
    public void dismiss() {
        mediaRelease();
        super.dismiss();
    }
}
